﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Threading;

namespace ART.Data
{
    public static class SqlHelper
    {

        public static readonly string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

        private static bool IsLog = false;
        private static object objlog = new object();

        private static void WLog(string log)
        {
            if (IsLog)
            {
                Monitor.Enter(objlog);
                System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory+DateTime.Now.ToString("yyyyMMdd") + ".txt", log + Environment.NewLine);
                Monitor.Exit(objlog);
            }
        }
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            return null;
        }
        #region __________执行带参数的Sql语句__________
        public static int GetRecordCount(string strTableName, string strWheres)
        {
            string cmdText = string.Format("select count(*) from {0} where {1}", strTableName, string.IsNullOrEmpty(strWheres) ? "1=1" : strWheres);
            return (int)ExecScalar(cmdText,new SqlParameter[0]);
        }

        public static int ExecNonQuery(string SQLString, params SqlParameter[] cmdParms)
        {
            return ExecNonQuery(SQLString, connectionString, cmdParms);
        }
        /// <summary>
        /// 执行一条SQL语句，返回影响行数。
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响行数val</returns>
        public static int ExecNonQuery(string SQLString, string connectionString,params SqlParameter[] cmdParms)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    int val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return val;
                }
            }
        }

        public static bool ExecNonQuery(List<string> Sqls)
        {
            return ExecNonQuery(Sqls, connectionString);
        }
        /// <summary>
        /// 执行Sql命令，调用SqlTransaction事务，返回bool值
        /// </summary>
        /// <param name="m_cmds">可变的SqlCommand数组，必须指定CommandText和CommandType</param>
        /// <returns>true或false</returns>
        public static bool ExecNonQuery(List<string> Sqls, string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlTransaction trans = connection.BeginTransaction())
                {
                    try
                    {
                        for (int i = 0; i < Sqls.Count; i++)
                        {
                            //WLog(Sqls[i]);
                            SqlCommand cmd = new SqlCommand(Sqls[i], connection, trans);//创建Command命令对象
                            cmd.ExecuteNonQuery();
                        }
                        trans.Commit();
                        return true;
                    }

                    #region ___catch___
                    catch (InvalidOperationException ept)
                    {
                        WLog("InvalidOperationException:" + ept.Message);
                        trans.Rollback();
                        return false;
                    }
                    catch (SqlException ept)
                    {
                        WLog("SqlException:" + ept.Message);
                        trans.Rollback();
                        return false;
                    }
                    catch (Exception ept)
                    {
                        WLog("Exception:" + ept.Message);
                        trans.Rollback();
                        return false;
                    }
                    finally
                    {
                        if (connection.State != ConnectionState.Closed)//确保数据库连接关闭
                            connection.Close();
                    }
                    #endregion
                }
            }

        }


        public static object ExecScalar(string SQLString, params SqlParameter[] cmdParms)
        {
            return ExecScalar(SQLString, connectionString, cmdParms);
        }
        /// <summary>
        /// 执行一条计算查询结果语句，返回首行首列（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object ExecScalar(string SQLString, string connectionString,params SqlParameter[] cmdParms)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj=null;
                        try
                        {
                             obj = cmd.ExecuteScalar();
                        }
                        catch(Exception e)
                        {
                           string s= e.Message;
                        }
                        cmd.Parameters.Clear();
                        return obj;

                    }
                    catch (SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        public static DataSet ExecDataSet(string SQLString, params SqlParameter[] cmdParms)
        {
            return ExecDataSet(SQLString, connectionString, cmdParms);
        }
        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecDataSet(string SQLString, string connectionString,params SqlParameter[] cmdParms)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        DataSet ds = new DataSet();
                        try
                        {
                            da.Fill(ds, "ds");
                            cmd.Parameters.Clear();
                        }
                        catch(SqlException e)
                        {
                            throw e;
                        }
                        return ds;
                    }
                }
            }
        }


         public static DataTable ExecDataTable(string SQLString, params SqlParameter[] cmdParms)
         {
             return ExecDataTable(SQLString, connectionString, cmdParms);
         }
        /// <summary>
        /// 执行查询语句，返回DataTable
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataTable</returns>
        public static DataTable ExecDataTable(string SQLString, string connectionString, params SqlParameter[] cmdParms)
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        try
                        {
                            da.Fill(dt);
                            cmd.Parameters.Clear();
                        }
                        catch (SqlException e)
                        {
                            throw e;
                        }
                        return dt;
                    }
                }
            }
        }



        public static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {

                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion




        #region __________存储过程操作__________


        public static DataSet ExecStoreDataSet(string storedProcName, IDataParameter[] parameters)
        {
            return ExecStoreDataSet(storedProcName, connectionString, parameters);
        }

        /// <summary>
        /// 执行存储过程，返回DataSet
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public static DataSet ExecStoreDataSet(string storedProcName, string connectionString, IDataParameter[] parameters)
        {
            using (DataSet ds = new DataSet())
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    using (SqlDataAdapter sda = new SqlDataAdapter())
                    {
                        sda.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                        sda.Fill(ds, "ds");
                        return ds;
                    }
                }
            }
        }


        public static int ExecStoreNonQuery(string storedProcName, IDataParameter[] parameters)
        {
            return ExecStoreNonQuery(storedProcName, connectionString, parameters);
        }
        /// <summary>
        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int ExecStoreNonQuery(string storedProcName, string connectionString, IDataParameter[] parameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                cmd = BuildIntCommand(connection, storedProcName, parameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        public static object ExecStoreScalar(string storedProcName, params SqlParameter[] parameters)
        {
            return ExecStoreScalar(storedProcName, connectionString, parameters);
        }
        /// <summary>
        /// 执行存储过程，返回首行首列（object）。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <returns>查询结果（object）</returns>
        public static object ExecStoreScalar(string storedProcName, string connectionString, params SqlParameter[] parameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                cmd = BuildIntCommand(connection, storedProcName, parameters);
                object obj = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return obj;
            }
        }

        public static int ExecStoreNonQueryWithReturnValue(string storedProcName, IDataParameter[] parameters)
        {
            return ExecStoreNonQueryWithReturnValue(storedProcName, connectionString, parameters);
        }
        /// <summary>
        /// 执行存储过程，返回 存储过程返回值	
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">存储过程返回值</param>
        /// <returns></returns>
        public static int ExecStoreNonQueryWithReturnValue(string storedProcName, string connectionString, IDataParameter[] parameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                connection.Open();
                cmd = BuildIntCommand(connection, storedProcName, parameters);
                cmd.ExecuteNonQuery();
               
                  return Convert.ToInt32(cmd.Parameters["@ReturnValue"].Value);
                }
                catch (SqlException ee)
                {
                    throw ee;
                }
            }
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }



        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)	
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }

        #endregion


        #region __________生成参数__________


        /// <summary>
        /// 创建输入参数
        /// </summary>
        public static SqlParameter MakeInParam(string ParamName, DbType DbType, int Size, object Value)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
        }

        /// <summary>
        /// 创建输出参数
        /// </summary>
        public static SqlParameter MakeOutParam(string ParamName, DbType DbType, int Size)
        {
            return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
        }

        public static SqlParameter MakeParam(string ParamName, DbType DbType, Int32 Size, ParameterDirection Direction, object Value)
        {
            SqlParameter param;

            if (Size > 0)
                param = new SqlParameter(ParamName, (SqlDbType)DbType, Size);
            else
                param = new SqlParameter(ParamName, (SqlDbType)DbType);

            param.Direction = Direction;
            if (!(Direction == ParameterDirection.Output && Value == null))
                param.Value = Value;

            return param;
        }

        #endregion 

    }
}
